﻿namespace BEGDC.CC.Web.UserControls.EV
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Collections;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.BL.CCFlow.EV;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.Entity;
    using BEGDC.Utility.Castle;
    using BEGDC.Utility.ExceptionManagement;
    using Nullables;
    using BEGDC.CC.BL.Workflow;

    /// <summary>
    ///		Summary description for ApproveMM.
    /// </summary>
    public class ApproveMM : BaseEV
    {
        protected System.Web.UI.HtmlControls.HtmlAnchor ibtnExport;
        protected System.Web.UI.WebControls.DataGrid dtGridASBAttendee;
        protected System.Web.UI.WebControls.DataGrid dtGridCustomerAttendee;
        protected System.Web.UI.WebControls.Label lblVenue;
        protected System.Web.UI.WebControls.Label lblTime;
        protected System.Web.UI.HtmlControls.HtmlTableCell VisitingPurpose;
        protected System.Web.UI.HtmlControls.HtmlTableCell MeetingContent;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.WebControls.DataGrid dtGridAP;

        protected System.Web.UI.WebControls.Button ibtnQuery;
        protected System.Web.UI.WebControls.Button ibtnReply;
        protected System.Web.UI.WebControls.Button ibtnReject;
        protected System.Web.UI.WebControls.Button ibtnSubmit;
        #region Property

        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }

        protected EVMeeting EVMeeting
        {
            get
            {
                if (Session[base.AppID + "MeetingMinutes"] == null)
                    return null;
                else
                    return Session[base.AppID + "MeetingMinutes"] as EVMeeting;
            }
            set
            {
                Session[base.AppID + "MeetingMinutes"] = value;
            }
        }
        protected int MeetingID
        {
            get
            {
                if (EVMeeting == null)
                    return 0;
                else
                    return EVMeeting.Id;
            }
        }
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!IsPostBack)
            {
                base.InitCommonData();
                InitAppData();
                //				Accessibility access = 	access = this.CheckAccessibility(WorkTransition.EV_CATApproveMM, BEGDC.CC.BL.Workflow.UserRole.CATDirector, HttpContext.Current.User.Identity.Name, this.AppID );			
                //				access = access | CheckAccessibility(WorkTransition.EV_PSOApproveMM, BEGDC.CC.BL.Workflow.UserRole.PSO, HttpContext.Current.User.Identity.Name, this.AppID );

                if (Access != null)
                    ControlStatusSetting(((EVAccessControl)Access).IsReadOnlyForApp);

                this.ibtnReject.Attributes["onclick"] = "javascript:OnReject();";
                this.ibtnReply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["flowid"] + ")");
                this.ibtnSubmit.Attributes["onclick"] = "javascript:OnApprove();";
                this.ibtnQuery.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["flowid"] + ")");

            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ibtnSubmit.Click += new EventHandler(ibtnSubmit_Click);
            this.ibtnReject.Click += new EventHandler(ibtnReject_Click);
            this.ibtnReply.Click += new EventHandler(ibtnReply_Click);
            this.ibtnQuery.Click += new EventHandler(ibtnQuery_Click);
            //this.ibtnExport.Click += new System.Web.UI.ImageClickEventHandler(this.ibtnExport_Click);
            this.dtGridAP.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dtGridAP_ItemDataBound);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void ControlStatusSetting(bool isReadonly)
        {
            if (isReadonly)
            {
                this.ibtnSubmit.Visible = false;
                this.ibtnQuery.Visible = false;
                this.ibtnReject.Visible = false;
                this.ibtnReply.Visible = true;
            }
            else
            {
                if (Access.IsQuery)
                {
                    this.ibtnSubmit.Visible = false;
                    this.ibtnReject.Visible = false;
                    this.ibtnReply.Visible = true;
                    this.ibtnQuery.Visible = false;
                }
                else
                {
                    this.ibtnReply.Visible = false;
                    this.ibtnQuery.Visible = true;
                }
            }
        }

        private void InitAppData()
        {
            InitEVMeeting();
            InitASBAttendee();
            InitCustomerAttendee();
            InitAPList();
        }

        private void InitEVMeeting()
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                IList meetingList = evService.GetEVMeetingByAppID(base.AppID);
                if (meetingList != null && meetingList.Count > 0)
                {
                    EVMeeting = meetingList[0] as EVMeeting;
                }
                if (EVMeeting != null)
                {
                    this.ibtnExport.Visible = true;
                    this.ibtnExport.HRef = "~/workflow/ExcelExport.aspx?MMID=" + this.MeetingID.ToString();

                    if (EVMeeting.Content + string.Empty != string.Empty)
                        this.MeetingContent.InnerHtml = EVMeeting.Content.Replace("\r\n", "<br>");
                    this.lblVenue.Text = EVMeeting.Venue;
                    if (EVMeeting.MeetingDate != Nullables.NullableDateTime.Default)
                        this.lblTime.Text = EVMeeting.MeetingDate.Value.ToString("MM/dd/yyyy");
                    if (EVMeeting.VisitingPurpose + string.Empty != string.Empty)
                        this.VisitingPurpose.InnerHtml = EVMeeting.VisitingPurpose.Replace("\r\n", "<br>");
                }
                else
                {
                    this.ibtnExport.Visible = false;
                }
            }
            catch (GDCException gdcEx)
            {
            }
        }
        private void InitASBAttendee()
        {
            try
            {
                IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                DataTable dtTable = queryService.QueryEVMeetingAttendee(base.AppID, true);
                this.dtGridASBAttendee.DataSource = dtTable;
                this.dtGridASBAttendee.DataBind();
            }
            catch (GDCException gdcEx)
            {
            }
        }
        private void InitCustomerAttendee()
        {
            try
            {
                IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                DataTable dtTable = queryService.QueryEVMeetingAttendee(base.AppID, false);
                this.dtGridCustomerAttendee.DataSource = dtTable;
                this.dtGridCustomerAttendee.DataBind();
            }
            catch (GDCException gdcEx)
            {
            }
        }
        private void InitAPList()
        {
            try
            {
                IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                DataTable dtTable = queryService.QueryAPListByMeetingID(this.MeetingID);

                this.dtGridAP.DataSource = dtTable;
                this.dtGridAP.DataBind();
            }
            catch (GDCException gdcEx)
            {

            }
        }

        void ibtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.ApproveMeetingMinutes(EVMeeting, null);
                // Add by Fan Ye
                SaveMMLink();
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {
                throw gdcEx;
            }

        }

        private void ibtnDrawback_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.Drawback(this.Application, null);
            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {

            }

        }

        void ibtnQuery_Click(object sender, EventArgs e)
        {
            if (this.tbOperationFlag.Text == "query")
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                string comment = string.Empty;
                if (Session["Comment"] != null)
                    comment = Session["Comment"].ToString();
                evService.Query(Convert.ToInt64(Request.QueryString["flowid"]), this.tbOperationContent.Text, comment);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
        }

        private void dtGridAP_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                ImageButton Btn_Edit = (ImageButton)e.Item.Cells[5].FindControl("btnEditAP");
                string ItemId = e.Item.Cells[0].Text.ToString();

                string statu = "Readonly";
                Btn_Edit.Attributes.Add("onclick", "AddActionPoint('" + ItemId + "','" + statu + "');");

            }
        }

        void ibtnReject_Click(object sender, EventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.RejectCheckApp(this.Application, WebUtility.DeCodeString(this.Server, this.tbComment.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //		private void ibtnExport_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        //		{
        //			try
        //			{
        //				ExcelTool.ICCExcelExport exportEVMeeting=new ExcelTool.ExportEVMeeting();
        //				exportEVMeeting.Export(this.Page, this.MeetingID );
        //			}
        //			catch
        //			{
        //				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.ErrorMessage.Export_0001 + "');</script>");
        //			}
        //		}

        void ibtnReply_Click(object sender, EventArgs e)
        {
            if (this.tbOperationFlag.Text == "reply")
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.ReplyQuery(Convert.ToInt64(Request.QueryString["flowid"]), WebUtility.DeCodeString(Server, this.tbOperationContent.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
        }

        private void SaveMMLink()
        {
            string fullpath = string.Empty;
            string appDocRoot = BEGDC.CC.BL.Workflow.Configuration.AttachmentPath;

            //Response.Write("appDocRoot --- " + appDocRoot);

            string relativePath = WebUtility.GetDocumentStoredPath(appDocRoot, "MeetingMinutes.xls", out fullpath);

            //Response.Write("relativePath --- " + relativePath);
            //Response.Write("fullpath --- " + fullpath);

            //string output = "appDocRoot --- " + appDocRoot + "<br/>" + "relativePath --- " + relativePath + "<br/>" + "fullpath --- " + fullpath + "<br/>";

            //Page.RegisterClientScriptBlock("", "<script>alert('" + output + "');</script>");
            ExcelTool.ExportEVMeeting excelExport = new ExcelTool.ExportEVMeeting();
            string output2 = excelExport.GenerateMMLinkFile(this.MeetingID, fullpath);
            //Response.Write(output2);
           // Page.RegisterClientScriptBlock("", "<script>alert('" + output2 + "');</script>");
            
            IUtility utiService = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
            IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            DataTable dtTable = queryService.QueryAPListByMeetingID(this.MeetingID);

            for (int i = 0; i < dtTable.Rows.Count; i++)
            {
                Attachment attach = new Attachment();
                attach.ActionPoint = new BEGDC.CC.Entity.ActionPoint();
                attach.ActionPoint.Id = Convert.ToInt32(dtTable.Rows[i]["APID"]);
                attach.FilePath = fullpath;
                attach.FileName = "MeetingMinutes.xls";
                attach.AttachmentType = utiService.GetDicItem(BEGDC.CC.BL.CCFlow.AttachmentType.OTHERS.ToString(), BEGDC.CC.BL.Common.DicType.ATTACHMENTTYPE);
                attach.Date = System.DateTime.Now;

                utiService.SaveAttachment(attach);
            }
        }

    }
}
